package com.macken.zjh.screens;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.delay;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.moveTo;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.parallel;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.removeActor;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.rotateTo;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.macken.zjh.Zjh;
import com.macken.zjh.constant.Constants;
import com.macken.zjh.entity.Desktop;
import com.macken.zjh.entity.Player;
import com.macken.zjh.network.req.ActionRequest;
import com.macken.zjh.network.req.DeskRequest;

public class GameScreen extends BaseScreen {

	Image gamebg;
	ImageButton btnM;// 跟注
	ImageButton btnA;// 加注
	ImageButton btnL;// 看牌
	ImageButton btnB;// 比牌
	ImageButton btnG;// 弃牌
	// ImageButton btnP;// 准备
	Button cancel;// 返回
	Window addDialog;
	Group btngroup;
	Stage stage;
	TextureAtlas btnAltas;// 游戏按钮
	TextureAtlas addAtlas;// 加注选项
	TextureAtlas pokerAtlas;// 扑克图片
	Image[] images;
	public Desktop desktop;

	BitmapFont bf;
	ClickListener cklistener;

	float accum = 0f;
	float interal = 1.0f / 30.0f;
	int array[] = { 1, 3, 5, 8, 10 };
	ImageButton btns[] = new ImageButton[5];

	int[] positions = { 640, 320, 660, 160, 420, 140, 120, 235, 140, 390 };
	int[] pokerpos = { 640, 320, 660, 160, 420, 140, 120, 235, 140, 390 };
	int[] preparePositions = { 640, 320, 660, 160, 420, 140, 120, 235, 140, 390 };

	public GameScreen(Zjh game) {
		super(game);
	}

	public void init(Desktop desktop) {
		this.desktop = desktop;

	}

	@Override
	public void show() {

		cklistener = new ClickListener() {
			public void clicked(InputEvent event, float x, float y) {
				float px = Gdx.input.getX();
				System.out.println("cklistener:" + x + " px:" + px);
			}
		};
		bf = new BitmapFont();

		stage = new Stage(WIDTH, HEIGHT, false);
		Gdx.input.setInputProcessor(stage);

		TextureRegion bg = load("gamebg.png", 800, 480);
		gamebg = new Image(new TextureRegionDrawable(bg));
		stage.addActor(gamebg);

		btngroup = new Group();
		btngroup.setVisible(false);
		stage.addActor(btngroup);

		btnAltas = new TextureAtlas(Gdx.files.internal("gamebtn.pack"));
		addAtlas = new TextureAtlas(Gdx.files.internal("gameadd.pack"));
		int x = 20;
		int y = 0;

		btnM = new ImageButton(getButtonStyle(btnAltas, "game_mbtn1",
				"game_mbtn2", "game_mbtn3"));
		btnM.setPosition(x, y);

		btnM.addListener(new ClickListener() {
			public void clicked(InputEvent event, float x, float y) {
				System.out.println("out:" + x);
				if (btnM.isDisabled()) {
					btnM.setDisabled(false);
				} else {
					btnM.setDisabled(true);
				}
			}
		});
		// stage.addActor(btnM);
		btngroup.addActor(btnM);

		x = (int) (btnM.getX() + btnM.getWidth() + 10);
		btnA = new ImageButton(getButtonStyle(btnAltas, "game_abtn1",
				"game_abtn2", "game_abtn3"));
		btnA.setPosition(x, y);

		// btnA.setDisabled(true);
		btnA.addListener(new ClickListener() {
			public void clicked(InputEvent event, float x, float y) {
				addDialog.toFront();
			}
		});
		// stage.addActor(btnA);
		btngroup.addActor(btnA);

		x = (int) (btnA.getX() + btnA.getWidth() + 10);
		btnL = new ImageButton(getButtonStyle(btnAltas, "game_lbtn1",
				"game_lbtn2", "game_lbtn3"));
		btnL.setPosition(x, y);
		// btnL.setDisabled(false);
		btnL.addListener(cklistener);
		// stage.addActor(btnL);
		btngroup.addActor(btnL);

		x = (int) (btnL.getX() + btnL.getWidth() + 10);
		btnB = new ImageButton(getButtonStyle(btnAltas, "game_bbtn1",
				"game_bbtn2", "game_bbtn3"));
		btnB.setPosition(x, y);
		// stage.addActor(btnB);
		btngroup.addActor(btnB);

		x = (int) (btnB.getX() + btnB.getWidth() + 10);
		btnG = new ImageButton(getButtonStyle(btnAltas, "game_gbtn1",
				"game_gbtn2", "game_gbtn3"));
		btnG.setPosition(x, y);
		btnG.addListener(cklistener);
		// stage.addActor(btnG);
		btngroup.addActor(btnG);

		TextureRegion addbg = addAtlas.findRegion("game_addbg");
		addDialog = new Window("", new Window.WindowStyle(bf, Color.BLACK,
				new TextureRegionDrawable(addbg)));
		addDialog.setWidth(addbg.getRegionWidth());
		addDialog.setHeight(addbg.getRegionHeight());

		stage.addActor(addDialog);
		addDialog.toBack();
		addDialog.align(Align.left);
		// addDialog.setVisible(false);
		load();

		TextureRegion cancelbg = new TextureRegion(new Texture(
				Gdx.files.internal("cancel.png")), 68, 51);
		cancel = new Button(new TextureRegionDrawable(cancelbg));
		cancel.setX(682);
		cancel.setY(480 - 5 - cancelbg.getRegionHeight());
		cancel.addListener(new ClickListener() {
			public void clicked(InputEvent event, float x, float y) {
				game.setScreen(new MenuScreen(game));
			}
		});
		stage.addActor(cancel);

		pokerAtlas = new TextureAtlas(Gdx.files.internal("poker.pack"));

		// btnP = new ImageButton(new TextureRegionDrawable(
		// btnAltas.findRegion("game_ready1")));
		// btnP.getStyle().imageDisabled = new TextureRegionDrawable(
		// btnAltas.findRegion("game_ready2"));
		// btnP.addListener(new ClickListener() {
		// public void clicked(InputEvent event, float x, float y) {
		//
		// ActionRequest ar = new ActionRequest();
		// ar.did = 0;
		// ar.pid = 100;
		// ar.action = Constants.ACTION_FOLLOW;
		// ar.value = 0;
		// game.socketAcceptor.write(ar);
		// // TestRequest request = new TestRequest();
		// // request.setPid(123);
		// // request.setS("macken");
		// // game.socketAcceptor.write(request);
		// // btnP.setDisabled(true);
		// // int[] player = { 5, 1, 2 };
		// // sendcard(player);
		// // btnP.addAction(sequence(delay(1f), removeActor()));
		// }
		// });
		// btnP.setPosition(400 - btnP.getWidth() / 2, 140);
		// stage.addActor(btnP);

		renderDesk();

	}

	@Override
	public void render(float delta) {
		Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		stage.act(delta);
		stage.draw();

	}

	@Override
	public void hide() {

	}

	@Override
	public void dispose() {
		stage.dispose();
		btnAltas.dispose();
		addAtlas.dispose();
	}

	public TextureRegionDrawable get(TextureAtlas altas, String name) {
		return new TextureRegionDrawable(altas.findRegion(name));
	}

	public ImageButtonStyle getButtonStyle(TextureAtlas btnAltas, String up,
			String down, String disable) {
		TextureRegionDrawable updr = get(btnAltas, up);
		TextureRegionDrawable downdr = get(btnAltas, down);
		TextureRegionDrawable disabledr = get(btnAltas, disable);
		ButtonStyle bs = new ButtonStyle();
		bs.up = updr;
		bs.down = downdr;
		bs.disabled = disabledr;
		ImageButtonStyle ibs = new ImageButtonStyle(bs);
		return ibs;
	}

	public ImageButtonStyle getButtonStyle(TextureAtlas btnAltas, String up,
			String disable) {
		TextureRegionDrawable updr = get(btnAltas, up);
		TextureRegionDrawable disabledr = get(btnAltas, disable);
		ButtonStyle bs = new ButtonStyle();
		bs.up = updr;
		bs.disabled = disabledr;
		ImageButtonStyle ibs = new ImageButtonStyle(bs);
		return ibs;
	}

	public void load() {
		for (int i = 0; i < array.length; i++) {
			int tmp = array[i];
			// btns[i] = new ImageButton(getButtonStyle(addAtlas, "add"+tmp,
			// "add"+tmp, "game_addbg5"));
			// btns[i].setName(String.valueOf(tmp));
			// btns[i].padLeft(40);

			TextureRegionDrawable region = new TextureRegionDrawable(
					addAtlas.findRegion("add" + tmp));

			btns[i] = new ImageButton(region);
			btns[i].getStyle().imageDisabled = new TextureRegionDrawable(
					addAtlas.findRegion("game_addbg5"));
			btns[i].setBackground(region);

			btns[i].setName(String.valueOf(tmp));
			btns[i].padLeft(40);
			// btns[i].setBackground(new TextureRegionDrawable(region))

			if (tmp < 5) {
				btns[i].setDisabled(true);
			} else {
				btns[i].addListener(new ClickListener() {
					public void clicked(InputEvent event, float x, float y) {

						for (int i = 0; i < array.length; i++) {
							float ox = Gdx.input.getX();
							ox = ox * 800 / Gdx.graphics.getWidth();
							float px = btns[i].getX();
							float pex = btns[i].getX() + btns[i].getWidth();
							if (px < ox && pex > ox) {
								System.out.println(btns[i].getName());
							}
						}
					}
				});
			}
			addDialog.add(btns[i]);
		}
		ImageButton closebtn = new ImageButton(new TextureRegionDrawable(
				addAtlas.findRegion("add_close")));
		closebtn.padLeft(60);
		closebtn.padBottom(30);
		closebtn.addListener(new ClickListener() {
			public void clicked(InputEvent event, float x, float y) {
				addDialog.toBack();
			}
		});
		addDialog.add(closebtn);
	}

	public void sendCardAnimations(int[] pids) {
		sendcard(calcSendOrder(pids));
	}

	/**
	 * 接收到发牌指令 生成发牌顺序 然后将结果传递给sendcard函数
	 */
	public int[] calcSendOrder(int[] pids) {
		int[] order = new int[pids.length];
		for (int i = 0; i < pids.length; i++) {
			order[i] = desktop.playerMap.get(pids[i]).clientPos;
		}
		return order;
	}

	/**
	 * 发牌的位置顺序 pos 为clientpos位置 pos {1,2,5}给1、2、5位置顺序发牌 例如{5,1,2}给5、1、2位置发牌
	 * 
	 * @param pos
	 */
	public void sendcard(int[] pos) {
		float duration = 0.3f;
		TextureRegion pr = pokerAtlas.findRegion("game_poker");
		TextureRegionDrawable p = new TextureRegionDrawable(pr);
		int mx = 400 - pr.getRegionWidth() / 2;
		int my = 480 - pr.getRegionHeight() - 40;
		images = new Image[pos.length * 3 + 1];
		for (int i = 0; i < images.length; i++) {
			images[i] = new Image(p);
			images[i].setPosition(mx, my);
			stage.addActor(images[i]);
		}
		float starttime = 1f;

		for (int y = 0; y < 3; y++) {
			for (int z = 0; z < pos.length; z++) {
				int index = pos[z] - 1;
				float ex = positions[index * 2] + y * 10;
				float ey = positions[index * 2 + 1];

				int rotate = 90;
				if (ex < 400) {
					rotate = -90;
				}
				images[z + y * pos.length].addAction(sequence(
						delay(starttime),
						parallel(moveTo(ex, ey, duration),
								rotateTo(rotate, duration))));
				starttime += duration;
			}

		}
		Action complete = new Action() {
			public boolean act(float delta) {
				for (int i = 0; i < images.length; i++) {
					images[i].addAction(removeActor());
				}
				desktop.state = Constants.DESK_STATE_DOING;
				renderDesk();
				btngroup.setVisible(true);
				return true;
			}
		};
		images[images.length - 1].addAction(sequence(delay(starttime),
				parallel(removeActor(), complete)));

	}

	/**
	 * 根据玩家状态渲染玩家卡牌信息 是否看牌 是否放弃 看牌 未看牌
	 * 
	 * 放弃 未放弃
	 * 
	 */
	public void renderDesk() {
		renderPlayerInfo();
		switch (desktop.state) {
		case Constants.DESK_STATE_READY:
			renderDeskReady(true);
			break;
		case Constants.DESK_STATE_SEND:
			renderDeskReady(false);
			break;
		case Constants.DESK_STATE_DOING:
			renderDeskReady(false);
			break;
		case Constants.DESK_STATE_END:
			renderDeskReady(false);
			break;
		default:
			break;
		}
		// for (int i = 0; i < desktop.getPlayers().length; i++) {
		// Player p = desktop.getPlayers()[i];
		// if (p.pokerImg == null) {
		// System.out.println(p.clientPos);
		// int x = positions[(p.clientPos - 1) * 2];
		// int y = positions[(p.clientPos - 1) * 2 + 1];
		// if (p.clientPos == 3) {
		// p.pokerImg = new Image(new TextureRegionDrawable(
		// pokerAtlas.findRegion("game_poker_normal")));
		// } else {
		// p.pokerImg = new Image(new TextureRegionDrawable(
		// pokerAtlas.findRegion("game_poker_normal")));
		// }
		// p.pokerImg.setPosition(x, y);
		// stage.addActor(p.pokerImg);
		// }
		// }
	}

	public void renderPlayerInfo() {
		for (int i = 0; i < desktop.players.size(); i++) {
			Player p = desktop.players.get(i);

			int x = preparePositions[(p.clientPos - 1) * 2] + 10;
			int y = preparePositions[(p.clientPos - 1) * 2 + 1] + 30;

			if (p.nickname == null) {
				TextFieldStyle style = new TextFieldStyle(bf, Color.WHITE,
						null, null, null);
				p.nickname = new TextField(String.valueOf(p.pid), style);
				p.nickname.setPosition(x, y);
				stage.addActor(p.nickname);
			}
		}
	}

	public void renderDeskReady(boolean isVisual) {
		if (isVisual) {
			for (int i = 0; i < desktop.players.size(); i++) {
				Player p = desktop.players.get(i);
				if (p.state == Constants.PLAYER_STATE_READY) {
					int x = preparePositions[(p.clientPos - 1) * 2];
					int y = preparePositions[(p.clientPos - 1) * 2 + 1];
					if (p.prepareImg == null) {
						p.prepareImg = getImage(btnAltas, "game_ready");
						p.prepareImg.setPosition(x, y);
						stage.addActor(p.prepareImg);
					}

					if (p.btnP != null) {
						p.btnP.addAction(removeActor());
					}

				} else if (p.state == Constants.PLAYER_STATE_IDLE
						&& p.clientPos == 3) {
					if (p.btnP == null) {
						p.btnP = new ImageButton(getDrawable(btnAltas,
								"game_ready1"), getDrawable(btnAltas,
								"game_ready2"));

						p.btnP.addListener(new ClickListener() {
							public void clicked(InputEvent event, float x,
									float y) {
								ActionRequest ar = new ActionRequest();
								ar.did = desktop.did;
								ar.pid = Zjh.pid;
								ar.action = Constants.ACTION_PREPARE;
								ar.value = 0;
								game.socketAcceptor.write(ar);
							}
						});
						stage.addActor(p.btnP);
					}
				}
			}
		} else {
			for (int i = 0; i < desktop.players.size(); i++) {
				Player p = desktop.players.get(i);
				if (p.prepareImg != null) {
					p.prepareImg.addAction(removeActor());
				}

				if (p.clientPos == 3 && p.btnP!=null) {
						p.btnP.addAction(removeActor());
				}
			}
		}

	}
}
